package com.wing.sell.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.area.model.entity.Area;
import com.wing.area.service.AreaService;
import com.wing.common.utils.JsonResult;
import com.wing.sell.dao.CustomersInfoDao;
import com.wing.sell.model.entity.*;
import com.wing.sell.model.request.CustomersInfoForm;
import com.wing.sell.model.response.CustomersInfoSearchVo;
import com.wing.sell.model.response.CustomersInfoVO;
import com.wing.sell.service.AgentService;
import com.wing.sell.service.CustomerClueSourceService;
import com.wing.sell.service.CustomerContactPostService;
import com.wing.sell.service.CustomersInfoService;
import com.wing.user.feign.UserClient;
import com.wing.user.model.request.User;
import com.wing.user.model.response.UserVO;
import com.wing.web.excel.CustomerExcelIn;
import com.wing.web.excel.DownExcelUtil;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 客户信息-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class CustomersInfoServiceImpl extends ServiceImpl<CustomersInfoDao, CustomersInfo> implements CustomersInfoService {

    @Autowired
    private AreaService areaService;
    @Autowired
    private CustomerContactPostService customerContactPostService;
    @Autowired
    private CustomerClueSourceService customerClueSourceService;
    @Autowired
    private AgentService agentService;
    @Autowired
    private UserClient userClient;

    @Override
    @Transactional
    public int add(CustomersInfoForm customersInfoForm) {
        //校验
        CustomersInfo customersInfo = new CustomersInfo();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(CustomersInfo.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(customersInfoForm, customersInfo, copyOptions);
        customersInfo.setCreator(JwtUtils.getLoginUserId());
        customersInfo.setCreatorName(JwtUtils.getLoginUsername());
        customersInfo.setCreateTime(LocalDateTime.now());
        customersInfo.setCompanyInfoId(JwtUtils.getEnterpriseId());
        return baseMapper.insert(customersInfo);
    }

    @Override
    public List<CustomersInfoVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<CustomersInfoVO> pageList4app(Page page, Map<String, Object> params) {
        List<CustomersInfoVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public CustomersInfoVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    public List<CustomersInfoVO> leadList(Long id) {
        return baseMapper.leadList(id);
    }

    @Override
    public void templetDown(HttpServletResponse response, HttpServletRequest request, String[] headerArr, String[] indexArr) throws IOException {
        List<String[]> downData = new ArrayList<>();
        StringBuffer tempStr = new StringBuffer();

        //客户类型
        for (CustomersInfo.CustomerType customerType : CustomersInfo.CustomerType.values()) {
            tempStr.append(customerType.getDesc()).append(",");
        }
        tempStr.delete(tempStr.length() - 1, tempStr.length());
        downData.add(tempStr.toString().split(","));
        tempStr.delete(0, tempStr.length());

        //审批人
        JsonResult<List<UserVO>> jsonResult = userClient.getAll();
        for (UserVO userVO : jsonResult.getData()) {
            tempStr.append(userVO.getNickname()).append(",");
        }
        tempStr.delete(tempStr.length() - 1, tempStr.length());
        downData.add(tempStr.toString().split(","));
        tempStr.delete(0, tempStr.length());

        //所属代理经销商
        QueryWrapper<Agent> agentQueryWrapper = new QueryWrapper<>();
        agentQueryWrapper.eq("status", 3);
        List<Agent> agentList = agentService.list(agentQueryWrapper);
        if (ObjectUtils.isEmpty(agentList)) {
            tempStr.append("无,");
        }else {
            for (Agent agent : agentList) {
                tempStr.append(agent.getName()).append(",");
            }
        }
        tempStr.delete(tempStr.length() - 1, tempStr.length());
        downData.add(tempStr.toString().split(","));
        tempStr.delete(0, tempStr.length());

        //业务员
        JsonResult<List<UserVO>> jsonResult2 = userClient.getAll();
        for (UserVO userVO : jsonResult2.getData()) {
            tempStr.append(userVO.getNickname()).append(",");
        }
        tempStr.delete(tempStr.length() - 1, tempStr.length());
        downData.add(tempStr.toString().split(","));
        tempStr.delete(0, tempStr.length());

        //职务
        List<CustomerContactPost> customerContactPostList = customerContactPostService.list();
        for (CustomerContactPost customerContactPost : customerContactPostList) {
            tempStr.append(customerContactPost.getName()).append(",");
        }
        tempStr.delete(tempStr.length() - 1, tempStr.length());
        downData.add(tempStr.toString().split(","));
        tempStr.delete(0, tempStr.length());

        //线索来源
        List<CustomerClueSource> customerClueSourceList = customerClueSourceService.list();
        for (CustomerClueSource customerClueSource : customerClueSourceList) {
            tempStr.append(customerClueSource.getName()).append(",");
        }
        tempStr.delete(tempStr.length() - 1, tempStr.length());
        downData.add(tempStr.toString().split(","));
        tempStr.delete(0, tempStr.length());


        DownExcelUtil.createExcelTemplate(response, request, "客户导入模板", Arrays.asList(headerArr), downData, Arrays.asList(indexArr));
    }


    @Override
    @Transactional
    public JsonResult importFile(List<CustomerExcelIn> list) {
        //遍历Excel表每一行的数据
        for (CustomerExcelIn customerExcelIn : list) {
            //判断必要字段不能为空
            String customerType = customerExcelIn.getCustomerType();
            if (StringUtils.isBlank(customerExcelIn.getCode())) {
                log.info("客户编码为空" + customerExcelIn);
                return JsonResult.fail("客户编码不能为空");
            }
            if (StringUtils.isBlank(customerType)) {
                log.info("客户类型为空" + customerExcelIn);
                return JsonResult.fail("客户类型不能为空");
            }
            if (StringUtils.isBlank(customerExcelIn.getCustomerName())) {
                log.info("客户名称为空" + customerExcelIn);
                return JsonResult.fail("客户名称不能为空");
            }
            if (StringUtils.isBlank(customerExcelIn.getLicenseNo())) {
                log.info("营业执照为空" + customerExcelIn);
                return JsonResult.fail("营业执照不能为空");
            }


         /*   if (StringUtils.isBlank(customerExcelIn.getClueSource())) {
                log.info("线索来源为空" + customerExcelIn);
                return JsonResult.fail("线索来源不能为空");
            }
            if (StringUtils.isBlank(customerExcelIn.getPost())) {
                log.info("职务为空" + customerExcelIn);
                return JsonResult.fail("职务不能为空");
            }
            if (StringUtils.isBlank(customerExcelIn.getApprover())) {
                log.info("审批人为空" + customerExcelIn);
                return JsonResult.fail("审批人不能为空");
            }
            if (StringUtils.isBlank(customerExcelIn.getSelAgt())) {
                log.info("代理商为空" + customerExcelIn);
                return JsonResult.fail("代理商不能为空");
            }
            if (StringUtils.isBlank(customerExcelIn.getSalesman())) {
                log.info("业务员为空" + customerExcelIn);
                return JsonResult.fail("业务员不能为空");
            }
*/

            //客户类型设值
            CustomersInfo customersInfo = new CustomersInfo();
            if (CustomersInfo.CustomerType.formal.getDesc().equals(customerType)) {
                log.info("该客户类型为正式客户", customerType);
                customersInfo.setCustomerType(CustomersInfo.CustomerType.formal);
            } else if (CustomersInfo.CustomerType.Intended.getDesc().equals(customerType)) {
                log.info("该客户类型为意向客户", customerType);
                customersInfo.setCustomerType(CustomersInfo.CustomerType.Intended);
            } else {
                log.info("该客户类型为潜在客户", customerType);
                customersInfo.setCustomerType(CustomersInfo.CustomerType.potential);
            }

            //判断是否已存在客户
            QueryWrapper<CustomersInfo> customersInfoQueryWrapper = new QueryWrapper<>();
            customersInfoQueryWrapper.eq("customer_type", customersInfo.getCustomerType());
            customersInfoQueryWrapper.eq("customer_name", customerExcelIn.getCustomerName());
            CustomersInfo exists = baseMapper.selectOne(customersInfoQueryWrapper);
            if (ObjectUtils.isEmpty(exists)) {

                //省、市、区设值
                if (StringUtils.isNotBlank(customerExcelIn.getAffiliatingArea())) {
                    log.info("拆分省/市/区");
                    String[] affiliatingArea = customerExcelIn.getAffiliatingArea().split("/");

                    for (int i = 0; i < affiliatingArea.length; i++) {
                        QueryWrapper<Area> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("areaname", affiliatingArea[i]);
                        Area area = areaService.getBaseMapper().selectOne(queryWrapper);
                        if (ObjectUtils.isEmpty(area)) {
                            log.error("地区信息查询为空，参数:{}", customerExcelIn.getAffiliatingArea());
                            return JsonResult.fail("省/市/区参数有误,请检查：" + customerExcelIn.getAffiliatingArea());
                        }

                        if (area.getLevel() == 1) {
                            customersInfo.setProvince(area.getId().longValue());
                        } else if (area.getLevel() == 2) {
                            customersInfo.setCity(area.getId().longValue());
                        } else if (area.getLevel() == 3) {
                            customersInfo.setArea(area.getId().longValue());
                        }
                    }

                }

                UserVO userVO;
                //获取审批人信息
                JsonResult<UserVO> approver = userClient.findUserByName(customerExcelIn.getApprover());
                if (approver.getCode() == 200) {
                    userVO = approver.getData();
                    customersInfo.setApprover(userVO.getId());
                    customersInfo.setApproverName(userVO.getNickname());
                } else {
                    log.error("审批人参数：{}", customerExcelIn.getApprover());
                    return JsonResult.fail("审批人信息查询失败,请联系管理员");
                }
                //获取业务员信息
                JsonResult<UserVO> salesman = userClient.findUserByName(customerExcelIn.getSalesman());
                if (salesman.getCode() == 200) {
                    userVO = salesman.getData();
                    customersInfo.setSalesmanId(userVO.getId());
                    customersInfo.setSalesmanName(userVO.getNickname());
                } else {
                    log.error("业务员参数：{}", customerExcelIn.getApprover());
                    return JsonResult.fail("业务员信息查询失败,请联系管理员");
                }
                //代理商设值
                QueryWrapper<Agent> agentQueryWrapper = new QueryWrapper<>();
                agentQueryWrapper.eq("name", customerExcelIn.getSelAgt());
                Agent agent = agentService.getBaseMapper().selectOne(agentQueryWrapper);
                if (ObjectUtils.isEmpty(agent)) {
                    log.info("未查询到值，代理商名称：" + customerExcelIn.getSelAgt());
                    return JsonResult.fail("请确认代理商是否填写正确！");
                }
                customersInfo.setSelAgtId(agent.getId());

                //职务设值
                QueryWrapper<CustomerContactPost> contactPostQueryWrapper = new QueryWrapper<>();
                contactPostQueryWrapper.eq("name", customerExcelIn.getPost());
                CustomerContactPost customerContactPost = customerContactPostService.getBaseMapper().selectOne(contactPostQueryWrapper);
                if (ObjectUtils.isEmpty(customerContactPost)) {
                    log.info("未查询到值，职务名称：" + customerExcelIn.getPost());
                    return JsonResult.fail("请确认职务是否填写正确！");
                }
                customersInfo.setPostId(customerContactPost.getId());

                //线索来源设值
                QueryWrapper<CustomerClueSource> clueSourceQueryWrapper = new QueryWrapper<>();
                clueSourceQueryWrapper.eq("name", customerExcelIn.getClueSource());
                CustomerClueSource customerClueSource = customerClueSourceService.getBaseMapper().selectOne(clueSourceQueryWrapper);
                if (ObjectUtils.isEmpty(customerClueSource)) {
                    log.info("未查询到值，来源名称：" + customerExcelIn.getClueSource());
                    return JsonResult.fail("请确认线索来源是否填写正确！");
                }
                customersInfo.setClueSourceId(customerClueSource.getId());

                customersInfo.setCreator(JwtUtils.getLoginUserId());
                customersInfo.setCreatorName(JwtUtils.getLoginUsername());
                customersInfo.setCustomerName(customerExcelIn.getCustomerName());
                customersInfo.setLicenseNo(customerExcelIn.getLicenseNo());
                customersInfo.setAddress(customerExcelIn.getAddress());
                customersInfo.setContactName(customerExcelIn.getContactName());
                customersInfo.setDepartment(customerExcelIn.getDepartment());
                customersInfo.setTelephone(customerExcelIn.getTelephone());
                customersInfo.setWechatNumber(customerExcelIn.getWechatNumber());
                customersInfo.setEmail(customerExcelIn.getEmail());
                customersInfo.setReferees(customerExcelIn.getReferees());
                customersInfo.setDosage(customerExcelIn.getDosage());
                customersInfo.setCompanyInfoId(JwtUtils.getEnterpriseId());

                baseMapper.insert(customersInfo);
            } else {
                log.error("customerType: {} customerName: {} is exists", customerExcelIn.getCustomerType(), customerExcelIn.getCustomerName());
                return JsonResult.fail("客户：" + exists.getCustomerName() + "已存在，请勿重复添加");
            }
        }
        return JsonResult.success("导入成功");
    }

    /**
     * 获取客户详情
     *
     * @param id
     * @return
     */
    @Override
    public CustomersInfoSearchVo getCustomersDetail(Long id) {
        return baseMapper.getCustomersDetail(id);
    }


}
